<template>
	<div class="Trace">
		<scroller :on-refresh="refresh" :on-infinite="infinite" :noDataText="noDataText" ref="scrollerTrace">
			<group id="scrollerTrace" class="scrollerTrace">
				<card v-for="(item,index) in items"
				      @touchstart.native="showDeleteButton(index, item)"
				      @touchend.native="clearLoop(item.id)">
					<div slot="content" class="card-padding">
						<p style="color:black;font-size:13px;line-height: 0.5">
							{{ item.name }}

						</p>
						<p style="color:#999;font-size:10px;line-height: 0.5">{{ item.time }}</p>
						<p style="font-size:13px;line-height:1.2;word-break: break-all;">{{ item.content }}</p>
						<!--<span v-show="item.file_url != null" class="audioBar" @click="playAudio(item.file_url, index)">
							<img slot="icon" style="width: 13px" src="@/assets/svg/icon_audio1.svg">
							<span style="padding-left: 5px; font-size: 13px" v-show="index == curIndex && leftTime != null">{{leftTime}}秒</span>
						</span>
						<spinner v-show="index == curIndex" type="lines" size="15px" @click.native="playAudio(item.file_url, index)"></spinner>-->
						<span v-show="item.file_url != null" class="audioBar" @click="play(index)">
							<img slot="icon" style="width: 13px" src="@/assets/svg/icon_audio1.svg">
							<span style="padding-left: 5px; font-size: 13px" v-show="index == curIndex">{{duration - currentTime}}秒</span>
						</span>
						<spinner v-show="(index == curIndex) && showSpin" type="lines" size="15px"></spinner>
						<audio :src="item.file_url" controls="controls" preload :id="index" hidden></audio>
						<!--<span @click="control(index)">播放/暂停</span>-->
					</div>
				</card>
			</group>
		</scroller>
	</div>
</template>

<script>
	import Vue from 'vue'
	import axios from 'axios'
	import NetWorking from '../../../utils/networking'
	import { Group, Cell, ConfirmPlugin, Tab, TabItem, Card, Spinner} from 'vux'
	import VueScroller from 'vue-scroller'
	Vue.use(VueScroller)
	Vue.use(ConfirmPlugin)

	const SIZE = 20

	export default {
		name: "scrollerSimple",
		components: {
			Group,
			Cell,
			Tab,
			TabItem,
			Card,
			Spinner
		},
    props: {
      curURL: {
        type: String,
        default: ''
      },
      jumpToObjectDetails: {
        type: String,
        default: ''
      },
      delRestURL: {
        type: String,
        default: ''
      }
    },
		data() {
			return {
				curIndex: -1,
				leftTime: null,
				showSpin: false,
				noDataText: '',
				offset: 0,
				limit: SIZE,
				noMoreData: false,
				items: [],
				itemName: 'name',
				isPlaying: false,
				my_media: null,
				media_timer: null,
				currentTime: 0,
				duration: null,
				audio: null
			}
		},
		watch: {
			curURL: function () {
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.scrollerTrace.finishPullToRefresh(false)
				this.$refs.scrollerTrace.finishInfinite(false)
			}
		},
		methods:{
			resetAudio(){
				if(this.audio && !this.audio.paused){
					this.audio.pause()
				}

				if(this.media_timer) {
					clearInterval(this.media_timer)
				}
				this.media_timer = null
				this.showSpin = false
				this.curIndex = -1
				this.duration = null
				this.currentTime = 0
			},
			playAudio(index) {
				let _this = this
				this.curIndex = index
				this.audio = document.getElementById(index)
				if(isNaN(_this.audio.duration)){
					alert('录制时间太短！')
					this.resetAudio()
					return
				}else{
					this.audio.load()
					this.audio.oncanplay = function () {
						_this.duration = parseInt(_this.audio.duration)
						_this.audio.play()
						_this.showSpin = true
						_this.media_timer = setInterval(function() {
							_this.currentTime = parseInt(_this.audio.currentTime)
							if(_this.audio.ended){
								_this.resetAudio()
							}
						},1000)
					}
				}
			},
			play(index) {
				if(index != this.curIndex){
					this.resetAudio()
					this.playAudio(index)
				}else{
					if(this.audio.paused){
						this.audio.play()
						this.showSpin = true
					}else{
						this.audio.pause()
						this.showSpin = false
					}
					return
				}
			},
			/*playAudio(url, index) {
				debugger
				if(this.isPlaying){
					if(this.curIndex == index){
						if (this.my_media){
							clearInterval(this.media_timer)
							this.media_timer = null
							this.showSpin = false
							this.leftTime = null
							this.curIndex = -1
							this.isPlaying = false
							this.my_media.stop()
							this.my_media.release()
						}
					}
					return
				}else{
					this.isPlaying = true
				}

				let duration = -1
				let fileTransfer = new FileTransfer()
				let uri = encodeURI(url)
				let fileURL = "cdvfile://localhost/persistent/path/to/downloads/"

				let _this = this
				_this.showSpin = true
				fileTransfer.download(
					uri,
					fileURL,
					function(entry) {
						_this.curIndex = index
						//If we go here, means the downloading is successful, and ready for play
						_this.media_timer = null
						_this.my_media = new Media(entry.toURL(),
							// success callback
							function () {
								console.log("playAudio():Audio Success")
							},
							// error callback
							function (err) {
								console.log("playAudio():Audio Error: " + err)
							}
						)
						_this.my_media.play()


						// Update my_media position every second
						if (_this.media_timer == null) {
							_this.media_timer = setInterval(function() {
								_this.duration = _this.my_media.getDuration()
								// get my_media position
								_this.my_media.getCurrentPosition(
									// success callback
									function(position) {
										if (position != -0.001) {
											_this.leftTime = parseInt(_this.duration - position)
											console.log("剩余" + parseInt(_this.duration - position) + " sec")
											//setAudioPosition((position) + " sec");
										}else{
											if (_this.my_media) {
												_this.my_media.stop()
												_this.my_media.release()
											}
											clearInterval(_this.media_timer)
											_this.media_timer = null
											_this.showSpin = false
											_this.leftTime = null
											_this.curIndex = -1
											_this.isPlaying = false
										}
									},
									// error callback
									function(e) {
										_this.showSpin = false
										console.log("Error getting pos=" + e);
										//setAudioPosition("Error: " + e);
									}
								);
							}, 1000);
						}
					},
					function(error) {
						console.log("download error source " + error.source);
						console.log("download error target " + error.target);
						console.log("download error code" + error.code);
					},
					false,
					{
						headers: {
							"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
						}
					}
				)
			},*/
			triggerrefresh()
			{
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.scrollerTrace.finishPullToRefresh(false)
				this.$refs.scrollerTrace.finishInfinite(false)
				this.infinite(done)
			},
			refresh (done) {
				this.$refs.scrollerTrace.finishPullToRefresh(true)
				return
			},
			infinite (done) {
				if(this.noMoreData){
					this.$refs.scrollerTrace.finishInfinite(true)
					return
				}else{
					let _this = this
					_this.offset += 1
					this.isRunning = true
					NetWorking.doGet(
						this.curURL,
						null ,
						{
							params:{
								offset: _this.offset,
								limit: _this.limit
							}
						}
					).then(
						response => {
							let res = response.data
							if (res.error_code == 0) {
								if(res.page_info.list.length >= 0){
									_this.items.push.apply(_this.items, res.page_info.list)
									_this.bottom += res.page_info.list.length
									//set noMoreData flag to true if current size < limit
									if(res.page_info.list.length < _this.limit){
										_this.noMoreData = true
										_this.$refs.scrollerTrace.finishInfinite(true);
									}
								}
							} else {
								alert(res.error_message)
							}
							done()
						}
					)
				}
			},
			jumpTo: function (id) {
				//组件间传递参数
				this.$router.push({ name: this.jumpToObjectDetails, params: { id: id }})
			},
			showDeleteButton(index, item) {
		    if(this.delRestURL == ''){
		    	return
		    }

				let hasAdminRole = false
				for(var i=0; i < this.$store.state.user.userModel.sysRoleList.length; i++){
					if(this.$store.state.user.userModel.sysRoleList[i].role_name == 'admin'){
						hasAdminRole = true
					}
				}
				if(hasAdminRole == false){
					return
				}

				var _this = this;
				clearInterval(this.Loop); //再次清空定时器，防止重复注册定时器
				this.Loop = setTimeout(function() {
					let thisObj = this
					thisObj.$vux.confirm.show({
						title: '系统提示',
						content: '确认要删除吗?',
						onConfirm () {
							NetWorking.doDelete(
								_this.delRestURL,
								null,
								{
									params: {
										id: item.id
									}
								}
							).then(
								response => {
									let rs = response.data
									if(rs.error_code == 0){
										_this.items.splice(index, 1);
									}else{
										alert(rs.error_message);
									}
								}
							)
						}
					})
				}.bind(this), 1000);
			},
			clearLoop(id) {
				clearInterval(this.Loop);
			}
		}
	}
</script>

<style>
	.scrollerTrace {
		margin-top: 240px;
		margin-left: 5px;
	}
	.cellTrace {
		padding: 0px 15px!important;
	}

	.card-padding {
		padding: 15px;
	}

	.scrollerTrace > .weui-cells > .weui-panel {
		margin-bottom: 0 !important;
		margin-top: 0 !important;
	}

	.scrollerTrace > .weui-panel__bd > .vux-card-content > .card-padding {
		border-bottom: 1px solid #eceef0 !important;
		box-shadow: 0 1px 1px #fff !important;
	}

	.audioBar {
		background: yellowgreen;
		color: white;
		padding-top: 5px;
		padding-bottom: 0px;
		padding-left: 10px;
		padding-right: 60px;
		border-radius: 5px;
		font-size: 13px;
		margin-top: 20px;
	}
</style>
